package com.ruoyi.demo.service.impl;

import java.util.List;
import java.util.Date;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.demo.mapper.AuctionOrderMapper;
import com.ruoyi.demo.domain.AuctionOrder;
import com.ruoyi.demo.domain.vo.AuctionOrderVO;
import com.ruoyi.demo.service.IAuctionOrderService;
import com.ruoyi.demo.service.IAuctionGoodsService;
import com.ruoyi.demo.service.IAuctionRecordService;
import com.ruoyi.demo.domain.AuctionGoods;
import com.ruoyi.demo.domain.AuctionRecord;
import org.springframework.transaction.annotation.Transactional;

/**
 * 订单Service业务层处理
 *
 * @author metaee
 * @date 2025-02-24
 */
@Service
public class AuctionOrderServiceImpl implements IAuctionOrderService
{
    @Autowired
    private AuctionOrderMapper auctionOrderMapper;

    @Autowired
    private IAuctionGoodsService auctionGoodsService;

    @Autowired
    private IAuctionRecordService auctionRecordService;

    /**
     * 查询订单
     *
     * @param orderId 订单主键
     * @return 订单
     */
    @Override
    public AuctionOrder selectAuctionOrderByOrderId(Long orderId)
    {
        return auctionOrderMapper.selectAuctionOrderByOrderId(orderId);
    }

    /**
     * 查询订单列表
     *
     * @param auctionOrder 订单
     * @return 订单
     */
    @Override
    public List<AuctionOrder> selectAuctionOrderList(AuctionOrder auctionOrder)
    {
        return auctionOrderMapper.selectAuctionOrderList(auctionOrder);
    }

    /**
     * 查询订单列表（包含额外信息）
     *
     * @param auctionOrder 订单
     * @return 订单VO集合
     */
    @Override
    public List<AuctionOrderVO> selectAuctionOrderVOList(AuctionOrder auctionOrder)
    {
        return auctionOrderMapper.selectAuctionOrderVOList(auctionOrder);
    }

    /**
     * 查询订单（包含额外信息）
     *
     * @param orderId 订单主键
     * @return 订单VO
     */
    @Override
    public AuctionOrderVO selectAuctionOrderVOByOrderId(Long orderId)
    {
        return auctionOrderMapper.selectAuctionOrderVOByOrderId(orderId);
    }

    /**
     * 新增订单
     *
     * @param auctionOrder 订单
     * @return 结果
     */
    @Override
    public int insertAuctionOrder(AuctionOrder auctionOrder)
    {
        return auctionOrderMapper.insertAuctionOrder(auctionOrder);
    }

    /**
     * 修改订单
     *
     * @param auctionOrder 订单
     * @return 结果
     */
    @Override
    public int updateAuctionOrder(AuctionOrder auctionOrder)
    {
        return auctionOrderMapper.updateAuctionOrder(auctionOrder);
    }

    /**
     * 批量删除订单
     *
     * @param orderIds 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteAuctionOrderByOrderIds(Long[] orderIds)
    {
        return auctionOrderMapper.deleteAuctionOrderByOrderIds(orderIds);
    }

    /**
     * 删除订单信息
     *
     * @param orderId 订单主键
     * @return 结果
     */
    @Override
    public int deleteAuctionOrderByOrderId(Long orderId)
    {
        return auctionOrderMapper.deleteAuctionOrderByOrderId(orderId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int createDealOrder(Long goodsId) {
        // 1. 获取商品信息
        AuctionGoods goods = auctionGoodsService.selectAuctionGoodsByGoodsId(goodsId);
        if (goods == null) {
            throw new ServiceException("商品不存在");
        }

        // 检查商品是否已经成交
        AuctionOrder existOrder = new AuctionOrder();
        existOrder.setGoodsId(goodsId);
        List<AuctionOrder> existOrders = auctionOrderMapper.selectAuctionOrderList(existOrder);
        if (existOrders != null && !existOrders.isEmpty()) {
            throw new ServiceException("该商品已经成交");
        }

        // 2. 获取最高出价记录
        AuctionRecord record = new AuctionRecord();
        record.setGoodsId(goodsId);
        List<AuctionRecord> records = auctionRecordService.selectAuctionRecordList(record);
        if (records == null || records.isEmpty()) {
            throw new ServiceException("没有找到有效的竞拍记录");
        }

        // 获取最高出价的记录（买家）
        AuctionRecord highestBid = records.get(0);

        // 3. 创建订单
        AuctionOrder order = new AuctionOrder();
        order.setGoodsId(goodsId);
        order.setSellerId(goods.getUserId());
        order.setBuyerId(highestBid.getUserId());
        order.setFinalPrice(highestBid.getBidPrice());
        order.setPayStatus("0"); // 未支付
        order.setOrderStatus("0"); // 待付款

        return insertAuctionOrder(order);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int payOrder(Long orderId) {
        // 1. 查询订单信息
        AuctionOrder order = selectAuctionOrderByOrderId(orderId);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }

        // 2. 检查订单状态
        if ("1".equals(order.getPayStatus())) {
            throw new ServiceException("订单已支付");
        }

        // 3. 更新订单状态
        AuctionOrder updateOrder = new AuctionOrder();
        updateOrder.setOrderId(orderId);
        updateOrder.setPayStatus("1"); // 已支付
        updateOrder.setOrderStatus("1"); // 已完成
        updateOrder.setPayTime(DateUtils.getNowDate()); // 设置支付时间

        return updateAuctionOrder(updateOrder);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int cancelOrder(Long orderId) {
        // 1. 查询订单信息
        AuctionOrder order = selectAuctionOrderByOrderId(orderId);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }

        // 2. 检查订单状态
        if ("1".equals(order.getPayStatus())) {
            throw new ServiceException("订单已支付，无法取消");
        }

        // 3. 更新订单状态
        AuctionOrder updateOrder = new AuctionOrder();
        updateOrder.setOrderId(orderId);
        updateOrder.setOrderStatus("2"); // 已取消
        updateOrder.setCancelTime(DateUtils.getNowDate()); // 设置取消时间

        return updateAuctionOrder(updateOrder);
    }
}
